package de.zainodis.triplog.ui.task;

import android.content.Context;
import android.os.AsyncTask;

import java.util.Date;

import de.zainodis.triplog.data.DataProvider;
import de.zainodis.triplog.data.LocationEntry;
import de.zainodis.triplog.data.WeatherEntry;
import de.zainodis.triplog.data.sync.TriplogSyncAdapter;
import de.zainodis.triplog.ui.fragment.ForecastFragment;
import de.zainodis.triplog.util.DateTimeUtils;

/**
 * Created by fzarrai on 10/4/2014.
 */
public class WeatherLoader extends AsyncTask<Void, Void, WeatherEntry> {

    private Context context;
    private IAsyncTaskParent<WeatherEntry> parent;

    public WeatherLoader(Context context, IAsyncTaskParent<WeatherEntry> parent) {
        super();
        this.context = context;
        this.parent = parent;
    }

    @Override
    protected WeatherEntry doInBackground(Void... params) {
        WeatherEntry result = null;
        //First try to get the weather via the cache, if it fails, query the database for the weather
        if (DataProvider.getCurrentTrip() != null) {
            LocationEntry location = DataProvider.getCurrentTrip().getLocation();

            if (location.getWeatherCount() >= ForecastFragment.NUMBER_OF_DAYS) {
                result = location.getTodaysWeather();

                if (result == null) {
                    //Query the database
                    result = WeatherEntry.getByDate(context, DateTimeUtils.toDbDateString(new Date()));
                }
            }

            if(result == null){
                //Request weather update from the internet
                TriplogSyncAdapter.syncImmediately(context, location.getLocationSetting(), ForecastFragment.NUMBER_OF_DAYS);
            }
        }
        return result;
    }


    @Override
    protected void onPostExecute(WeatherEntry weather) {
        super.onPostExecute(weather);
        parent.onPostExecute(weather);
    }
}
